//
//  NetworkTools.m
//  ZoneTry
//
//  Created by youminuo on 16/5/27.
//  Copyright © 2016年 ZoneTry. All rights reserved.
//

#import "NetworkTools.h"

///  测试服务器
NSString *const Debug = @"http://api.zonetry.com/PLAT110";
///  发布服务器
NSString *const Production = @"http://api.zonetry.com/PLAT110T";

@protocol NetworkToolsProxy <NSObject>

@optional
/// AFN 内部的数据访问方法
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                         success:(void (^)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject))success
                                         failure:(void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure;;

@end

@interface NetworkTools ()<NetworkToolsProxy>

@end

@implementation NetworkTools

+ (instancetype)sharedTools{
    
    static NetworkTools *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:Debug]];
    });
    return instance;
}

- (instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        }];
        [self.reachabilityManager startMonitoring];
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain",@"text/html", nil];
        [(AFJSONResponseSerializer *)self.responseSerializer setRemovesKeysWithNullValues:YES];
    }
    return self;
}

- (void)request:(RequestMethod)method url:(NSString *)url params:(id)params callback:(void(^)(id resonse, NSError *error))callback{
    
    NSString *methodName = (method == GET) ? @"GET" : @"POST";
    [[self dataTaskWithHTTPMethod:methodName URLString:url parameters:params success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        callback(responseObject, nil);
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        callback(nil, error);
    }] resume];
}
@end
